class SoftLabel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [''],
            inputValues: {
                id: '',
                commCode: '',
                type: 'AREA_TYPE',
                name: '',
                chargeCycle: '',
                billDay: '',
                isEnable: 0,
                customContent: '',
                description: ''
            },
            floorAreaTypeList: [
                {
                    startFloor: 1,
                    endFloor: 1,
                    rate: ''
                }, {
                    startFloor: 2,
                    endFloor: 2,
                    rate: ''
                }
            ]
        };
        this.pageCount = 0;
    }

    componentDidMount() {
        this.verify = {
            name: function (value) {
                if (value.length < 2) {
                    return '公式名称至少得2个字符!';
                }
            },
            chargeCycle: function (value) {
                if (!value) {
                    return '收费周期必须填写！';
                }
            },
            billDay: function (value) {
                if (!value) {
                    return '账单日必须填写！';
                }
            }
        };
    }

    /* custom functions */
    updateList(page, pageSize) {
        let params = {};
        params.page = page;
        params.pageSize = pageSize;
        params.commCode = this.refs.commSelectSearch.commCode;
        postJson("/property/feeFormula/queryPropertyFeeFormulaPage.x", params, (data) => {
            let list = data.data.list;
            this.pageCount = data.data.size;
            this.setState({
                list: list
            });
        })
    }

    search() {
        this.updateList(1, 10);
    }

    addFormula() {
        this.refs.modal_add_property_fee_formula.show();
    }

    btnSubmit() {

        if (this.state.inputValues.type === 'FLOOR_AREA_TYPE') {
            let floorAreaTypeList = this.state.floorAreaTypeList;
            for (let i in floorAreaTypeList) {
                if (!floorAreaTypeList[i].rate) {
                    layer.msg(floorAreaTypeList[i].startFloor + '-' + floorAreaTypeList[i].endFloor + ' 费率不能为空！', {icon: 5});
                    return;
                }
            }
            this.state.inputValues.customContent = JSON.stringify(this.state.floorAreaTypeList);
        } else if (this.state.inputValues.type === 'AREA_TYPE') {
            if (!this.state.inputValues.customContent) {
                layer.msg('费率不能为空！', {icon: 5});
                return;
            }
        }
        postJson("/property/feeFormula/savePropertyFeeFormula.x", this.state.inputValues, () => {
            layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;添加成功', {icon: 6});
            this.updateList(1, 10);
            this.refs.modal_add_property_fee_formula.close();
        });
    }

    edit(formula) {
        this.state.inputValues = {
            id: formula.id,
            commCode: formula.commCode,
            type: formula.type,
            name: formula.name,
            chargeCycle: formula.chargeCycle,
            billDay: formula.billDay,
            isEnable: formula.isEnable,
            customContent: formula.type === 'AREA_TYPE' ? formula.customContent : '',
            description: formula.description
        };
        if (formula.type === 'FLOOR_AREA_TYPE') {
            this.state.floorAreaTypeList = JSON.parse(formula.customContent);
        }
        this.refs.modal_add_property_fee_formula.show();
        this.setState({});
    }

    delete(id) {
        layui.layer.confirm('确定要删除该公式?删除之后此公式无法使用!', (index) => {
            let param = {};
            param.id = id;
            postJson("/property/feeFormula/deletePropertyFeeFormula.x", $.param(param),
                () => {
                    this.updateList(1, 10);
                    layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;删除成功', {icon: 6});
                });
            layui.layer.close(index);
        });
    }

    endCallback() {
        this.setState({
            inputValues: {
                id: '',
                commCode: this.refs.commSelectModal.commCode,
                type: 'AREA_TYPE',
                name: '',
                chargeCycle: '',
                billDay: '',
                isEnable: 0,
                customContent: '',
                description: ''
            },
            floorAreaTypeList: [
                {
                    startFloor: 1,
                    endFloor: 1,
                    rate: ''
                }, {
                    startFloor: 2,
                    endFloor: 2,
                    rate: ''
                }
            ]
        });
    }

    enableFormula(e, formula) {
        console.log("aaaaaaaaaaa", e);
        postJson("/property/feeFormula/enableFormula.x", {
            id: formula.id,
            commCode: formula.commCode,
            isEnable: e
        }, () => {
            layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;成功', {icon: 6});
            this.updateList(1, 10);
        });
    }

    formulaChange() {
        this.setState({});
    }

    inputChange(isFloor, value, type, i) {
        if (isFloor) {
            this.state.floorAreaTypeList[i][type] = value;
        } else {
            this.state.inputValues[type] = value;
        }
        this.setState({});
    }

    onChangeFloorInputView(isDel, i) {
        if (isDel) {
            this.state.floorAreaTypeList.splice(i, 1);
        } else {
            this.state.floorAreaTypeList.push({
                startFloor: 1,
                endFloor: 1,
                rate: ''
            });
        }
        this.setState({});
    }

    floorTableView(type, customContent) {
        let view = [];
        if (type === 'AREA_TYPE') {
            view.push(<div>{customContent}/㎡</div>)
        } else if (type === 'FLOOR_AREA_TYPE') {
            let list = JSON.parse(customContent);
            for (let i in list) {
                view.push(<div>{list[i].startFloor + ' - ' + list[i].endFloor} 楼 {list[i].rate}/㎡</div>)
            }

        }
        return view;
    }

    floorAreaTypeView() {
        let view = [];
        let list = this.state.floorAreaTypeList;
        let len = list.length;
        for (let i = 0; i < len; i++) {
            let startFloor = parseInt(list[i].startFloor);
            if (i > 0 && startFloor <= parseInt(list[i - 1].endFloor)) {
                startFloor = parseInt(list[i - 1].endFloor) + 1;
                this.state.floorAreaTypeList[i].startFloor = startFloor;
            }
            let endFloor = parseInt(list[i].endFloor);
            if (endFloor < startFloor) {
                this.state.floorAreaTypeList[i].endFloor = startFloor;
                endFloor = startFloor;
            }
            view.push(<Item>
                {i === 0 ? <Label>楼层费率</Label> : ''}
                <div style={i > 0 ? {marginLeft: '110px'} : {}}>
                    <Input type="number"
                           frameStyle={{width: '50px'}}
                           value={startFloor}
                           onChange={(value) => this.inputChange(true, value, 'startFloor', i)}/>
                    <div style={{
                        float: 'left',
                        display: 'block',
                        padding: '4px 0',
                        marginRight: '5px',
                        marginLeft: '-5px'
                    }}>-
                    </div>
                    <Input type="number"
                           frameStyle={{width: '50px'}}
                           value={endFloor}
                           onChange={(value) => this.inputChange(true, value, 'endFloor', i)}/>
                    <Input type="text" frameStyle={{width: '56px'}}
                           placeholder="费率"
                           value={list[i].rate}
                           onChange={(value) => this.inputChange(true, value, 'rate', i)}/>
                    {i === 0 ? <Tips>填写楼层返回，如：1到5层，那么填写1和5</Tips>
                        : i === len - 1 ?
                            <i className="layui-icon layui-icon-add-circle"
                               style={{fontSize: '20px'}}
                               onClick={() => this.onChangeFloorInputView(false, i)}>&#xe61f;</i>
                            : <i className="layui-icon layui-icon-close-fill"
                                 style={{fontSize: '22px'}}
                                 onClick={() => this.onChangeFloorInputView(true, i)}>&#x1007;</i>}
                </div>
            </Item>)
        }

        return view;
    }

    render() {

        return (
            <Frame header="自定义物业缴费公式" headerBtns={
                <HeaderBtn onClick={() => this.addFormula()}><i className="fa fa-plus"/>&nbsp;新增公式</HeaderBtn>
            }
            >
                <Form type="pane">
                    <Item>
                        <LayuiCommSelect mask={['building', 'unit', 'floor', 'room']}
                                         formLabelName="所属小区"
                                         ref="commSelectSearch"
                                         onChangeComm={() => this.updateList(1, 10)}/>
                    </Item>
                    <Table ref="table" count={this.pageCount}
                           pageOnClick={(page, pageSize) => this.updateList(page, pageSize)}>
                        <thead>
                        <tr>
                            <th>公式名称</th>
                            <th>公式类型</th>
                            <th>收费周期</th>
                            <th>账单日</th>
                            <th>创建时间</th>
                            <th>费率</th>
                            <th>描述</th>
                            <th width="60">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {

                            this.state.list.map((array) => {
                                return <tr>
                                    <td>{array.name}</td>
                                    <td>{
                                        array.type === 'AREA_TYPE' ? '面积计费' :
                                            array.type === 'FLOOR_AREA_TYPE' ? '楼层面积阶梯计费' :
                                                array.type === 'MANUAL_AREA_TYPE' ? '人工录入计费' : '未知'}</td>
                                    <td>{array.chargeCycle}</td>
                                    <td>每月{array.billDay}号</td>
                                    <td>{array.creationTime}</td>
                                    <td>{
                                        array.type === 'AREA_TYPE' ? array.customContent + '/㎡' :
                                            array.type === 'FLOOR_AREA_TYPE' ? this.floorTableView(array.type, array.customContent) : ''
                                    }</td>
                                    <td>{array.description}</td>
                                    <td>
                                        <Button size="xs"
                                                onClick={() => this.edit(array)}>编辑</Button>
                                        <Button size="xs" btnType="danger"
                                                onClick={() => this.delete(array.id)}>删除</Button>
                                        <Checkbox
                                            title="启用"
                                            onClick={(e) => this.enableFormula(e, array)}
                                            checked={array.isEnable === 1}
                                            lay-skin="primary"/>
                                    </td>
                                </tr>
                            })
                        }
                        </tbody>
                    </Table>

                    <Modal
                        title="添加标签"
                        ref="modal_add_property_fee_formula"
                        rea={['500px']}
                        endCallback={() => this.endCallback()}>
                        <Form type="pane" size="sm" verify={() => {
                            return this.verify;
                        }}>

                            <Input type="hidden" value={this.state.inputValues.isEnable}/>
                            <Input type="hidden" value={this.state.inputValues.id}/>
                            <Item>
                                <Label>所属小区</Label>
                                <LayuiCommSelect
                                    mask={['building', 'unit', 'floor', 'room']}
                                    commCode={this.state.inputValues.commCode}
                                    commSelectShowStyle="BadgeWhenOneComm"
                                    ref="commSelectModal"
                                    onChangeComm={(value) => this.inputChange(false, value, 'commCode')}/>
                            </Item>

                            <Item>
                                <Label>公式类型</Label>
                                <Select ref="type"
                                        value={this.state.inputValues.type}
                                        onChange={(value) => this.inputChange(false, value, 'type')}>
                                    <option value="AREA_TYPE">面积计费</option>
                                    <option value="FLOOR_AREA_TYPE">楼层面积阶梯计费</option>
                                    <option value="MANUAL_AREA_TYPE">人工录入计费</option>
                                </Select>
                                <Tips>{'面积计费：<br/>' +
                                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;面积计算是按照房屋的建造面积计算物业费&nbsp;如：建筑面积是60平，费率为1.2那么每月物业费为60*1.2=72 <br/>' +
                                '楼层面积阶梯计费：<br/>' +
                                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;不同楼层费率不同，如：一个建筑面积是60平的房屋，1到5楼费率为每平方米1.2元、6到10层为每平方米1.5元&nbsp;' +
                                '其中3楼的物业费计算为：60*1.2=72&nbsp;而7楼的计算为：60*1.5=80 <br/>' +
                                '人工录入计费：<br/>' +
                                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;系统不再计算物业费，物业通过表格导入已有的物业缴费信息'
                                }</Tips>
                            </Item>
                            <Item>
                                <Label>公式名称</Label>
                                <Input type="text"
                                       name="name"
                                       value={this.state.inputValues.name}
                                       lay-verify="name"
                                       onChange={(value) => this.inputChange(false, value, 'name')}
                                       placeholder="请输入公式名称"
                                />
                            </Item>
                            <Item>
                                <Label>收费周期</Label>
                                <Input type="number"
                                       min="1"
                                       lay-verify="chargeCycle"
                                       value={this.state.inputValues.chargeCycle}
                                       onChange={(value) => this.inputChange(false, value, 'chargeCycle')}/>
                                <Tips>收费周期指物业费间隔时间，如：1个月收取一次那么收费周期就为1，3个月收取一次那么收费周期就为3</Tips>
                            </Item>
                            <Item>
                                <Label>账单日</Label>
                                <Input type="number"
                                       min="1"
                                       max="31"
                                       lay-verify="billDay"
                                       value={this.state.inputValues.billDay}
                                       onChange={(value) => this.inputChange(false, value, 'billDay')}/>
                                <Tips>账单日指物业账单生成时间，如：每个月5号生成物业缴费账单，那么账单日就为5</Tips>
                            </Item>
                            {this.state.inputValues.type === 'AREA_TYPE' ? <Item>
                                <Label>费率</Label>
                                <Input
                                    type="test"
                                    value={this.state.inputValues.customContent}
                                    onChange={(value) => this.inputChange(false, value, 'customContent')}/>
                                <Tips>费率指按建筑面积每平方米物业费价格如：每平方米1.5元那么费率就是1.5</Tips>
                            </Item> : this.state.inputValues.type === 'FLOOR_AREA_TYPE' ? this.floorAreaTypeView() : ''}
                            <Item style={{width: '290px'}}
                                  className="layui-form-item layui-form-text">
                                <Label>描述</Label>
                                <div className="layui-input-block" style={{marginTop: '-5px'}}>
                                    <textarea
                                        name="desc"
                                        placeholder="请输入描述"
                                        value={this.state.inputValues.description}
                                        className="layui-textarea"

                                        onChange={(e) => this.inputChange(false, e.target.value, 'description')}/>
                                </div>
                            </Item>
                            <Item>
                                <Button formBtn={true}
                                        size='sm'
                                        btnType='normal'
                                        lay-submit="true"
                                        onClick={() => this.btnSubmit()}>确定</Button>
                            </Item>
                        </Form>
                    </Modal>
                </Form>
            </Frame>
        )
    }
}

ReactDOM.render(
    <SoftLabel/>
    , document.getElementById('root'));
